#include <vector>
#include "ObjectPool.h"


class Test
{
public:
    Test() : x(0) { cout << "Test() 构造\n"; }
    Test(int n) : x(n) { cout << "Test(" << n << ") 构造\n"; }
    ~Test() { cout << "~Test() 析构\n"; }
    void show() { cout << "x = " << x << endl; }
private:
    int x;
};


struct TreeNode
{
    int _val;
    TreeNode *_left;
    TreeNode *_right;
    TreeNode()
        : _val(0), _left(nullptr), _right(nullptr)
    {
    }
};

// 测试内存池的函数
void TestObjectPool1()
{
    ObjectPool<Test> pool;

    cout << "---- 创建对象 ----" << endl;
    Test *p1 = pool.New();
    Test *p2 = pool.New();
    Test *p3 = pool.New();

    p1->show();
    p2->show();
    p3->show();

    cout << "---- 回收对象 ----" << endl;
    pool.Delete(p1);
    pool.Delete(p2);

    cout << "---- 再次申请对象（应该复用之前的内存） ----" << endl;
    Test *p4 = pool.New();
    Test *p5 = pool.New();

    p4->show();
    p5->show();

    // 最后别忘了释放
    pool.Delete(p3);
    pool.Delete(p4);
    pool.Delete(p5);
}

void TestObjectPool2()
{
    // 申请释放的轮次
    const size_t Rounds = 3;
    // 每轮申请释放多少次
    const size_t N = 100000;
    size_t begin1 = clock();
    std::vector<TreeNode *> v1;
    v1.reserve(N);
    for (size_t j = 0; j < Rounds; ++j)
    {
        for (int i = 0; i < N; ++i)
        {
            v1.push_back(new TreeNode);
        }
        for (int i = 0; i < N; ++i)
        {
            delete v1[i];
        }
        v1.clear();
    }
    size_t end1 = clock();
    ObjectPool<TreeNode> TNPool;
    size_t begin2 = clock();
    std::vector<TreeNode *> v2;
    v2.reserve(N);
    for (size_t j = 0; j < Rounds; ++j)
    {
        for (int i = 0; i < N; ++i)
        {
            v2.push_back(TNPool.New());
        }
        for (int i = 0; i < 100000; ++i)
        {
            TNPool.Delete(v2[i]);
        }
        v2.clear();
    }
    size_t end2 = clock();
    cout << "new cost time:" << end1 - begin1 << endl;
    cout << "object pool cost time:" << end2 - begin2 << endl;
}



int main()
{
    // TestObjectPool1();
    TestObjectPool2();
    return 0;
}
